package com.framework.utils.verified;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 功能描述:
 *
 * @author ck
 * @date 2018/10/25 14:21
 */
public class MathUtils {

    public static BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = new BigDecimal("0.00");
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                ret = new BigDecimal((String) value);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }

    /**
     * 格式化数字，500 --> 500.00
     * @param obj
     * @return
     */
    public static String formatToNumber(BigDecimal obj) {
        DecimalFormat df = new DecimalFormat("#.00");
        if (obj.compareTo(BigDecimal.ZERO) == 0) {
            return "0.00";
        } else if (obj.compareTo(BigDecimal.ZERO) > 0 && obj.compareTo(new BigDecimal(1)) < 0) {
            return "0" + df.format(obj);
        } else {
            return df.format(obj);
        }
    }


    public static String formatToMoney(String str) {
        Integer length = str.lastIndexOf(".") != -1 ? str.lastIndexOf(".") : str.length();
        return addDot(new StringBuilder(str), length - 3).toString();
    }

    private static StringBuilder addDot(StringBuilder sb, Integer index) {
        if (index > 0) {
            sb.insert(index, ",");
        }
        if (index >= 3) {
            addDot(sb, index - 3);
        }
        return sb;
    }

}
